package com.pers.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.pers.springcloud.bean.JsonResultVo;
import com.pers.springcloud.myhandler.CustomerBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author huangjian
 */
@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException")
    public JsonResultVo byResource() {
        return JsonResultVo.success("byResource success");
    }

    public JsonResultVo handleException(BlockException e) {
        return JsonResultVo.error(e.getClass().getCanonicalName() + "\t服务不可用");
    }

    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")
    public JsonResultVo byUrl() {
        return JsonResultVo.success("byUrl success");
    }

    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException2")
    public JsonResultVo customerBlockHandler() {
        return JsonResultVo.success("customerBlockHandler success");
    }

    /**
     * fallback 解决java运行时异常
     * blockHandler 处理sentinel设置的违规行为
     * exceptionsToIgnore 排除异常，发生该异常时不进行处理
     * 同时触发运行时异常与sentinel违规异常时优先处理违规异常
     *
     * @param id
     * @return
     */
    @GetMapping("/rateLimit/forBack")
    @SentinelResource(value = "forBack",
            fallbackClass = CustomerBlockHandler.class,
            fallback = "forBackHandlerException",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException",
            exceptionsToIgnore = {IllegalAccessException.class})
    public JsonResultVo forBack(@RequestParam(required = false, value = "id") Long id) {
        if (id != null && id == 1) {
            throw new RuntimeException("Param error");
        }
        return JsonResultVo.success("customerBlockHandler success");
    }

}
